// Copyright  2012 Petr TALLA. [petr.talla@gmail.com]
// This file is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This file is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY;  without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Lesser General Public License for more details.
// [http://www.gnu.org/copyleft/lesser.html]
//=============================================================================

package tc.crase.meta;

import tc.crase.db.Xattr;
import tc.crase.db.XattrGRP;
import tc.crase.db.XattrTPE;
import tc.crase.db.XattrSTR;
import tc.crase.db.XattrURL;
import tc.crase.sys.XobjectEx;

public class Attrdef {
	public Xattr.Type type;
	public String name;
	public int minCount;
	public int maxCount;
	public String value;
	
	public Attrdef(Xattr.Type type, String name, int minCount, int maxCount, String value) {
		this.type = type;
		this.name = name;
		this.minCount = minCount;
		this.maxCount = maxCount;
		this.value = value;
	}
	
	public void initialize(XobjectEx obj) {
		if (maxCount < 0) return;
		
		for (int i = 0; i < minCount; i++) {
			if ( type == Xattr.Type.TPE) {
				obj.attrAdd(new XattrTPE(name));
			}
			else if (type == Xattr.Type.STR) {
				obj.attrAdd(new XattrSTR(name, value));
			}
			else if (type == Xattr.Type.URL) {
				obj.attrAdd(new XattrURL(name, value));
			}
		}
		
		if ( (minCount > 0) && ( type == Xattr.Type.GRP) ) {
			obj.attrAdd(new XattrGRP(-1, obj));
		}
	}
	
	boolean isInstance(Xattr attr) {
		if (type ==Xattr.Type.TPE) {
			XattrTPE tpe = attr.getAsTPE();
			if (tpe == null) return false;
			if (value.equals(tpe.id)) return true;
			return false;
		}
		else if (type ==Xattr.Type.STR) {
			XattrSTR str = attr.getAsSTR();
			if (str == null) return false;
			if (name.equals(str.getName())) return true;
			return false;
		}
		else if (type ==Xattr.Type.URL) {
			XattrURL url = attr.getAsURL();
			if (url == null) return false;
			if (name.equals(url.getName())) return true;
			return false;
		}
		return false;
	}
	
	public boolean couldBeAdded(XobjectEx xo) {
		if (maxCount < 0) return true;
		
		int count = 0;
		
		//for (int i = 0; i < xo.attrCount(); i++) {
		for ( Xattr attr : xo ) {
			if ( isInstance(attr) ) count++; 
		}
		
		if (count < maxCount) return true;
		return false;
	}
}
